const fs = require('fs')
const path = require('path')
const crypto = require('crypto')
import { dialog } from 'electron'

// 扫描本地视频文件的函数
export const scanVideoFiles = (directory: string) => {
    return new Promise((resolve, reject) => {
        let videoFiles: any = []
        const videoExtensions = ['.mp4', '.avi', '.mkv']
        // 检查单个路径是否存在
        if (!fs.existsSync(directory)) {
            resolve({
                code: 404,
                message: '路径不存在'
            })
        } else {
            fs.readdir(directory, (err, files) => {
                if (err) {
                    reject(err)
                } else {
                    files.forEach((file) => {
                        const filePath = path.join(directory, file)
                        const fileExtension = path.extname(filePath)
                        if (videoExtensions.includes(fileExtension)) {
                            // 根据路径生成唯一 id 
                            const hash = crypto.createHash('sha256')
                            hash.update(filePath)
                            const uniqueId = hash.digest('hex')
                            const obj = {
                                uid: uniqueId,
                                path: filePath,
                                name: file
                            }
                            videoFiles.push(obj)
                        }
                    })
                    resolve({
                        code: 200,
                        data: videoFiles,
                        message: '成功获取视频文件'
                    })
                }
            })
        }
    })
}

// 选取本地文件路径
export const selectLocalFilePath = () => {
    // 打开文件夹选择对话框
    return dialog.showOpenDialog({
        properties: ['openDirectory']
    })
}

